# -*- coding: utf-8 -*-

'''
@project : SmartHomeVideo
@FileName: face_analysis_main
@Author  :linych 
@Time    :2021/2/23 14:18
@Desc  : 
'''


import os
import sys

sys.path.insert(0,os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import pika
import json
from FaceAnalysis.strange_recognite_task import StrangeRecogTask
from Core.redis_connecter import redis_con_dict,PARAM,TASK,PICTURE,VIDEO,TASK_NAME
import time
from Core import conf

host = conf.get('MQ','url')
username = 'test'
pwd = 'test'
user_pwd = pika.PlainCredentials(username, pwd)
queue = conf.get('MQ','queue')

# 建立连接，服务器地址为localhost，可指定ip地址
print(host)
# connection = pika.BlockingConnection(pika.ConnectionParameters(
#         host=host, credentials=user_pwd))
#
# print('connect...')
# # 建立会话
# channel = connection.channel()
#
# # 声明RPC请求队列
# channel.queue_declare(queue='rpc_queue')


def run(correlation_id,channel):

    arg_dict = redis_con_dict[PARAM].hgetall(correlation_id)

    routing_key = arg_dict.get('routing_key','')
    seqid = arg_dict.get('seqid','')
    deviceId = arg_dict.get('deviceId','')
    visitorId = arg_dict.get('visitorId','')

    pic_id_list = redis_con_dict[VIDEO].lrange(correlation_id, 0, -1)

    imageBase64s_list = redis_con_dict[PICTURE].mget(list(pic_id_list))



    result = StrangeRecogTask.run(seqid=seqid,deviceId=deviceId,visitorId=visitorId,imageBase64s_list=imageBase64s_list)

    print(result)
    channel.basic_publish(exchange='',
                         routing_key=routing_key,
                         properties=pika.BasicProperties(correlation_id = correlation_id),
                         body=str(result))



Time_List  = []

def face_main():
    global  Time_List

    connection = pika.BlockingConnection(pika.ConnectionParameters(
        host=host, credentials=user_pwd))

    # 建立会话
    channel = connection.channel()

    # 声明RPC请求队列
    channel.queue_declare(queue=queue)

    while True:

        
        correlation_id = redis_con_dict[TASK].lpop(TASK_NAME)


        if correlation_id is None:
            time.sleep(0.001)
            continue

        try:
            ss = time.time()

            print('analysis {}....'.format(correlation_id))
            run(correlation_id,channel)

            Time_List.append(time.time()-ss)
            print(' avg_time : {} len:{}'.format(sum(Time_List)/len(Time_List),len(Time_List)))

        except Exception as e:

            print('reconnect......')
            
            connection = pika.BlockingConnection(pika.ConnectionParameters(
                host=host, credentials=user_pwd))

            # 建立会话
            channel = connection.channel()

            # 声明RPC请求队列
            channel.queue_declare(queue=queue)

            print('analysis {}....'.format(correlation_id))
            run(correlation_id, channel)
            print('end ...')







if __name__ == '__main__':


    import threading

    threads = []

    w = 50

    for i in range(w):
        t = threading.Thread(target=face_main)
        threads.append(t)


    for i in range(w):
        threads[i].start()

    for i in range(w):

        threads[i].join()





